<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">

      <el-form-item label="客户名称" prop="partner_name">
        <el-input :style="{width: '120px'}" v-model="queryParams.partner_name" placeholder="请输入客户名称" clearable
                  @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="手机号" prop="mobile">
        <el-input :style="{width: '120px'}" v-model="queryParams.mobile" placeholder="请输入手机号" clearable
                  @keyup.enter.native="handleQuery"/>
      </el-form-item>

      <el-form-item label="售前阶段" prop="state">
        <el-select :style="{width: '120px'}" v-model="queryParams.state" placeholder="请选择售前阶段">
          <el-option v-for="dict in dict.type.customer_state" :key="dict.value" :label="dict.label"
                     :value="dict.value"></el-option>
        </el-select>
      </el-form-item>


      <el-form-item label="销售" prop="state">
        <el-select :style="{width: '120px'}" v-model="queryParams.user_id" placeholder="请选择销售">
          <el-option v-for="dict in dict.type.crm_sales" :key="dict.value" :label="dict.label"
                     :value="dict.value"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="跟单时间">
        <el-date-picker v-model="daterangenext_time" :style="{width: '200px'}" value-format="yyyy-MM-dd"
                        type="daterange"
                        range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
                   v-hasPermi="['crm:lead:add']">新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
                   v-hasPermi="['crm:lead:edit']">修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
                   v-hasPermi="['crm:lead:remove']">删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
                   v-hasPermi="['crm:lead:export']">导出
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-view" size="mini" @click="toDayLead(1)">今日跟单
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-view" size="mini" @click="toDayLead(2)">本周跟单
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-view" size="mini" @click="toDayLead(3)">本月跟单
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-user-solid" size="mini" @click="handlePrivilege"
                   v-hasPermi="['bd:partner:privilege']" v-if="isShow">跟单分配
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="leadList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="50" align="center"/>
      <el-table-column label="客户" align="center" prop="partner_name" width="70"/>
      <el-table-column label="手机号" align="center" prop="mobile" width="90">
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="addDefaultCustomer(scope.row)">
            {{ scope.row.mobile }}
          </el-button>
        </template>
      </el-table-column>
<!--      <el-table-column label="短信来源" align="center" prop="sms_source">-->
<!--        <template slot-scope="scope">-->
<!--          <dict-tag :options="dict.type.sms_channel_source" :value="scope.row.sms_source"/>-->
<!--        </template>-->
<!--      </el-table-column>-->

      <el-table-column label="意向产品" align="center" prop="intention_product_id" width="80">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.crm_product" :value="scope.row.intention_product_id"/>
        </template>
      </el-table-column>
      <el-table-column label="性别" align="center" prop="sex" width="80">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_user_sex" :value="scope.row.sex"/>
        </template>
      </el-table-column>
      <el-table-column label="用户来源" align="center" prop="source" width="80">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.customer_source" :value="scope.row.source"/>
        </template>
      </el-table-column>
      <el-table-column label="售前阶段" align="center" prop="state" width="80">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.customer_state" :value="scope.row.state"/>
        </template>
      </el-table-column>
      <el-table-column label="跟单时间" align="center" prop="next_time" width="80">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.next_time, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="跟进信息" align="center" prop="remark" width="180"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="160">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit-outline" @click="handleComment(scope.row)"
                     v-hasPermi="['crm:lead:edit']">跟进
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-info" @click="handleShowResumeTxt(scope.row)"
                     v-hasPermi="['crm:resume:query']">详情
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-info" @click="gotoOrder(scope.row)"
                     v-hasPermi="['bd:partner:edit']">订单
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                     v-hasPermi="['crm:lead:edit']">修改
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                     v-hasPermi="['crm:lead:remove']">删除
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="销售" align="center" prop="user_id">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.crm_sales" :value="scope.row.user_id"/>
        </template>
      </el-table-column>

      <el-table-column label="更新时间" align="center" prop="update_time" width="80">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.update_time, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="create_time" width="80">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.create_time, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="短信类型" align="center" prop="type">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.crm_sms_type" :value="scope.row.type"/>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
                @pagination="getList"/>

    <!-- 添加或修改订单跟踪对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">

        <el-row>
          <el-col span="12">
            <el-form-item label="客户" prop="partner_name">
              <el-input v-model="form.partner_name" readonly="readonly" placeholder="请选择客户">
                <el-button slot="append" @click="handleDictSelect('bd_partner')" icon="el-icon-search"></el-button>
              </el-input>
            </el-form-item>
            <el-form-item label="意向产品" prop="intention_product_id">
              <el-select v-model="form.intention_product_id" placeholder="请输入用户来源">
                <el-option v-for="dict in dict.type.crm_product" :key="dict.value" :label="dict.label"
                           :value="dict.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="短信类型" prop="type">
              <el-select v-model="form.type" placeholder="请输入短信类型">
                <el-option v-for="dict in dict.type.crm_sms_type" :key="dict.value" :label="dict.label"
                           :value="dict.value">
                </el-option>
              </el-select>
            </el-form-item>
<!--            <el-form-item label="短信来源" prop="sms_source"-->
<!--                          v-if="form.type != null && form.type != '' && form.type != '10'">-->
<!--              <el-select v-model="form.sms_source" placeholder="请选择短信来源" clearable>-->
<!--                <el-option-->
<!--                  v-for="dict in dict.type.sms_channel_source"-->
<!--                  :key="dict.value"-->
<!--                  :label="dict.label"-->
<!--                  :value="dict.value"-->
<!--                />-->
<!--              </el-select>-->
<!--            </el-form-item>-->
            <el-form-item label="用户来源" prop="source">
              <el-select v-model="form.source" placeholder="请输入用户来源">
                <el-option v-for="dict in dict.type.customer_source" :key="dict.value" :label="dict.label"
                           :value="dict.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col span="12">
            <el-form-item label="手机号" prop="mobile">
              <el-input v-model="form.mobile" readonly="readonly" replaceholder="请点击表格中客户手机号码选中客户后在新建跟单"/>
            </el-form-item>
            <el-form-item label="售前阶段" prop="state">
              <el-select v-model="form.state" placeholder="请选择状态">
                <el-option v-for="dict in dict.type.customer_state" :key="dict.value" :label="dict.label"
                           :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="跟单时间" prop="next_time">
              <el-date-picker clearable v-model="form.next_time" type="date" value-format="yyyy-MM-dd"
                              placeholder="请选择下次跟单时间">
              </el-date-picker>
            </el-form-item>

          </el-col>

        </el-row>

        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"/>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <CommentComponent v-if="commentYN" ref="CommentComponent" @close-dialog="handleCommentClose"/>
    <el-dialog title="详情" :visible.sync="dialogResumeTxt" @close="diaClose" width="40%">
      <el-form>
        <el-form-item label="简历全部信息" prop="resumeTxt">
          <el-input v-model="contentStr" type="textarea" resize="none" :rows="18" :readonly="true"/>
        </el-form-item>
      </el-form>
    </el-dialog>

    <el-dialog :title="title" :visible.sync="openPrivilege" width="500px">
      <el-form ref="form" label-width="80px">
        <el-col span="12">
          <el-form-item label="销售" prop="user_id">
            <el-select v-model="user_id" placeholder="请输入归属销售">
              <el-option v-for="dict in dict.type.crm_sales" :key="dict.value" :label="dict.label" :value="dict.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitPrivilege">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <dictSelect ref="dictSelect" @onDictSelectd="onDictSelectd"/>
  </div>

</template>


<script>
import {
  listlead,
  getlead,
  addlead,
  listComment,
  updatelead,
  dellead,
  getLeadTimeData,
  PutPrivilegelead
} from "../api/lead";
import store from '@/store';
import dictSelect from "../../components/dictSelect.vue";
import CommentComponent from './Comment';
import {
  getOneResume
} from "@/views/zxcrm/api/resume";
import {
  PutPrivilegeCustomer
} from "../../zxbd/api/partner";

export default {
  name: "lead",
  components: {
    dictSelect,
    CommentComponent
  },
  dicts: ['sms_channel_source', 'sys_user_sex', 'customer_state', 'crm_product', 'crm_sales', 'crm_sms_type', 'customer_source'],
  data() {
    return {
      defaultShow: false,
      isShow: false,
      openPrivilege: false,
      dialogResumeTxt: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 订单跟踪表格数据
      leadList: [],
      // 弹出层标题
      title: "",
      user_id: null,
      // 是否显示弹出层
      open: false,
      // 销售时间范围
      daterangenext_time: [],
      // 查询参数
      queryParams: {
        supervisorFlag: null,
        state: null,
        pageNum: 1,
        pageSize: 10,
        vendorName: null,
        id: null,
        partner_name: null,
        mobile: null,
        user_id: null,
        next_time: null,
        type: null,
        source: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        id: [{
          required: true,
          message: "客户不能为空",
          trigger: "blur"
        }],
        intention_product_id: [{
          required: true,
          message: "意向产品不能为空",
          trigger: "blur"
        }],
        state: [{
          required: true,
          message: "状态不能为空",
          trigger: "change"
        }],
        sms_source: [{
          required: true,
          message: "短信渠道不能为空",
          trigger: "change"
        }],
        type: [{
          required: true,
          message: "短信不能为空",
          trigger: "change"
        }]
      },
      commentYN: false
    };
  },
  created() {
    this.queryParams = this.$route.query;
    this.getList();
  },
  methods: {
    /** 查询订单跟踪列表 */
    getList() {
      if (this.queryParams.supervisorFlag != null) {
        getLeadTimeData(this.queryParams.supervisorFlag, this.queryParams.pageNum, this.queryParams.pageSize).then((
          response) => {
          this.leadList = response.rows;
          this.total = response.total;
          this.loading = false;
        })
      } else {
        this.loading = true;
        if (null != this.daterangenext_time && '' != this.daterangenext_time) {
          this.queryParams.beginnext_time = this.daterangenext_time[0];
          this.queryParams.endnext_time = this.daterangenext_time[1];
        }
        listlead(this.queryParams).then(response => {
          this.leadList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      }
    },
    // 取消按钮
    cancel() {
      this.openPrivilege = false;
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        partner_name: null,
        mobile: null,
        intention_product_id: null,
        state: null,
        next_time: null,
        remark: null,
        user_id: store.getters.userId,
        updateBy: null,
        update_time: null,
        sms_source: null,
        type: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams.supervisorFlag = null
      this.daterangenext_time = [];
      this.resetForm("queryForm");
      this.queryParams.id = null;
      this.queryParams.partner_name = null;
      this.queryParams.mobile = null;
      this.handleQuery();
    },
    //客户选择
    handleDictSelect(param) {
      var dictParams = {
        dict_type: param
      }
      if (param == 'bd_partner') {
        dictParams.tatle = '客户';
        dictParams.is_customer = '0';
      }
      this.$refs.dictSelect.show(dictParams);
    },
    //字典选择后
    onDictSelectd(param) {
      if (param != undefined && param != null) {
        this.form.id = param[0].dict_value;
        this.form.partner_name = param[0].dict_label;
        this.form.mobile = param[0].param1;
      }
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      console.log("选择的数据", selection)
      const arrs = []
      selection.forEach(e => {
        arrs.push(e.id)
      })
      this.userIds = arrs;
      this.isShow = selection.length === 0 ? this.defaultShow : true
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    // 添加默认用户到新增里
    addDefaultCustomer(row) {
      this.queryParams.id = row.id;
      this.queryParams.partner_name = row.partner_name;
      this.queryParams.mobile = row.mobile;
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.form.id = this.queryParams.id;
      this.form.partner_name = this.queryParams.partner_name;
      this.form.mobile = this.queryParams.mobile;
      this.title = "添加订单跟踪";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      console.log(row)
      this.reset();
      const ids = row.id || this.ids;
      getlead(ids).then(response => {
        this.form = response.data;
        this.form.partner_name = row.partner_name;
        this.form.mobile = row.mobile;
        this.open = true;
        this.title = "修改订单跟踪";
      });
    },
    toDayLead(id) {
      this.queryParams.supervisorFlag = id;
      getLeadTimeData(id, this.queryParams.pageNum, this.queryParams.pageSize).then((response) => {
        this.leadList = response.rows;
        this.total = response.total;
        this.loading = false;
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updatelead(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            this.$modal.msgSuccess("id不能为空！！");
            this.open = false;
            this.getList();
          }
        }
      });
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      console.log(row.id)
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除订单跟踪编号为"' + ids + '"的数据项？').then(function () {
        return dellead(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('crm/orderSupervisor/export', {
        ...this.queryParams
      }, `orderSupervisor_${new Date().getTime()}.xlsx`)
    },
    handlePrivilege() {
      this.user_id = null
      this.openPrivilege = true
      this.title = '分配归属'
    },
    //跳转到订单界面
    gotoOrder(row) {
      this.$router.push({
        path: '/crm/order/order',
        query: {
          id: row.id,
          name: row.name,
          mobile: row.mobile
        }
      });
      // this.$router.push({name:'orderSupervisor',params:{id:id}})
    },
    /** 查看客户信息详情 */
    handleShowResumeTxt(row) {
      if (row.mobile == null) {
        return $modal.errorInfo("手机号不能为空");
      }
      this.queryParams.mobile = row.mobile;
      getOneResume(this.queryParams).then(response => {
        this.dialogResumeTxt = true
        this.contentStr = response.data.resumeTxt
      });
    },
    //  订单跟踪信息
    handleComment(row) {
      this.commentYN = true
      this.$nextTick(() => {
        this.$refs.CommentComponent.open(row)
      }).finally(() => {
        this.getList()
      })
    },
    handleCommentClose() {
      this.commentYN = false;
    },
    submitPrivilege() {
      console.log(this.userIds, this.user_id)
      PutPrivilegelead(this.userIds, this.user_id).then(response => {
        this.openPrivilege = false
        this.getList()
      })
    }
  }
};
</script>
